package com.wanglibao.woodtrade.woodtrade.ui.activity.user;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.google.gson.Gson;
import com.wanglibao.woodtrade.woodtrade.R;
import com.wanglibao.woodtrade.woodtrade.config.NetConfig;
import com.wanglibao.woodtrade.woodtrade.jsonrpc.JsonRPCAsyncTask;
import com.wanglibao.woodtrade.woodtrade.model.User;
import com.wanglibao.woodtrade.woodtrade.model.impl.UserImpl;
import com.wanglibao.woodtrade.woodtrade.ui.activity.BaseActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.HomeActivity;
import com.wanglibao.woodtrade.woodtrade.util.CommonUtil;
import com.wanglibao.woodtrade.woodtrade.util.ToastUtil;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RegisterActivity extends BaseActivity {

    @Bind(R.id.rl_common_title)
    RelativeLayout rlCommonTitle;
    @Bind(R.id.edit_activity_register_phone)
    EditText editActivityRegisterPhone;
    @Bind(R.id.edit_activity_register_code)
    EditText editActivityRegisterCode;
    @Bind(R.id.edit_activity_register_password)
    EditText editActivityRegisterPassword;
    @Bind(R.id.btn_activity_register_getcode)
    Button btn_activity_register_getcode;

    @Bind(R.id.btn_activity_register_register)
    Button btn_activity_register_register;

    @Bind(R.id.cb_activity_register_agreement)
    CheckBox cb_activity_register_agreement;
    public boolean isGetPhoneCode = false;

    @Bind(R.id.sv_activity_register_view)
    ScrollView sv_activity_register_view;

    TimeCount timeCount;
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.arg2 != 2){
                if (msg.arg1 == NetConfig.TaskId.userRegister){
                    String phone = editActivityRegisterPhone.getText().toString();
                    String password = editActivityRegisterPassword.getText().toString();
                    JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(RegisterActivity.this, NetConfig.SERVER+NetConfig.TYPE_USER,
                            NetConfig.userLogin,handler,"jsonObject",NetConfig.TaskId.userLogin,new Object[]{phone,password});
                    jsonRPCAsyncTask.execute(new Void[]{});
                }else if (msg.arg1 == NetConfig.TaskId.getUserPhoneCode){
                    isGetPhoneCode = true;
                    timeCount = new TimeCount(60000,1000);
                    timeCount.start();
                }else if (msg.arg1 == NetConfig.TaskId.userLogin){
                    UserImpl userImpl = new UserImpl(RegisterActivity.this);
                    userImpl.deleteAll();
                    User user = new Gson().fromJson(msg.obj.toString(), User.class);
                    user.password = editActivityRegisterPassword.getText().toString();
                    userImpl.insert(user);
                    startActivity(new Intent(RegisterActivity.this, HomeActivity.class));
                    finish();
                }
            }

            return false;
        }
    });
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 19) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            rlCommonTitle.setPadding(0, 0, 0, 0);
        }
        tvTitle.setText("注册");
        addViewClicklistener(tvBack);

        cb_activity_register_agreement.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    btn_activity_register_register.setClickable(true);
                    btn_activity_register_register.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_login_btn));
                }else{
                    btn_activity_register_register.setClickable(false);
                    btn_activity_register_register.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_login_btn_noclick));
                }
            }
        });

        if (Build.VERSION.SDK_INT >= 19) {
            final View decorView = getWindow().getDecorView();
            decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    Rect rect = new Rect();
                    decorView.getWindowVisibleDisplayFrame(rect);
                    int screenHeight = decorView.getRootView().getHeight();
                    int height = screenHeight - rect.bottom;
                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) sv_activity_register_view.getLayoutParams();
                    layoutParams.setMargins(0, 0, 0, height);
                    sv_activity_register_view.requestLayout();
                }
            });
        }
    }

    @OnClick(R.id.btn_activity_register_getcode) void onBtnActivityRegisterGetcodeClick() {
        String phone = editActivityRegisterPhone.getText().toString();
        if (!TextUtils.isEmpty(phone)){
            if (CommonUtil.isPhone(phone)){
                JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(RegisterActivity.this, NetConfig.SERVER+NetConfig.TYPE_USER,
                        NetConfig.getUserPhoneCode,handler,"jsonObject",NetConfig.TaskId.getUserPhoneCode,
                        new Object[]{phone,"1"});
                jsonRPCAsyncTask.execute(new Void[]{});
            }else{
                ToastUtil.createLongToast(this,"手机号填写错误");
            }
        }else{
            ToastUtil.createLongToast(RegisterActivity.this,"请输入手机号");
        }
    }

    @OnClick(R.id.tv_activity_register_agreement_text) void onAgreementTextClick(){
        startActivity(new Intent(this,AgreementActivity.class));
    }

    @OnClick(R.id.btn_activity_register_register) void onBtnActivityRegisterRegisterClick() {
        String phone = editActivityRegisterPhone.getText().toString();
        String phoneCode = editActivityRegisterCode.getText().toString();
        String password = editActivityRegisterPassword.getText().toString();
        if (!TextUtils.isEmpty(phone) && !TextUtils.isEmpty(phoneCode) && !TextUtils.isEmpty(password)
                && isGetPhoneCode){
            JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(RegisterActivity.this, NetConfig.SERVER+NetConfig.TYPE_USER,
                    NetConfig.userRegister,handler,"jsonObject",NetConfig.TaskId.userRegister,
                    new Object[]{phone,password,phoneCode});
            jsonRPCAsyncTask.execute(new Void[]{});
        }else{
            ToastUtil.createLongToast(RegisterActivity.this,"资料不完整");
        }
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            btn_activity_register_getcode.setText("重新获取");
            btn_activity_register_getcode.setClickable(true);
            btn_activity_register_getcode.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_register_getphonecode));
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            btn_activity_register_getcode.setClickable(false);
            btn_activity_register_getcode.setText(millisUntilFinished / 1000 + "秒");
            btn_activity_register_getcode.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_register_getphonecode_noclick));
        }
    }

    @OnClick(R.id.tv_activity_register_login)
    void loginClick(){
        onBackPressed();
    }
}
